<?php
/**
 * Created by PhpStorm.
 * User: liuwei
 * Date: 2022/12/16
 * Time: 14:13
 */

namespace App\Services\Company\Models;

use App\Services\Member\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Company extends Model
{

    use HasFactory;


    protected $table = 'company';

    protected $fillable = [
        'id', 'user_id', 'name', 'category_id', 'is_bind_mini', 'logo', 'address', 'contact', 'contact_qrcode', 'background', 'uuid', 'mobile', 'role_id','expired_at', 'is_trial_version','corp_id', 'work_wechat_id', 'introduction', 'description', 'coordinates'
    ];


    protected $appends = [
        'expired_days', 'is_expired'
    ];

    public function getExpiredAtAttribute($value)
    {
        // 使用 Carbon 类来格式化日期，只显示日期部分
        return Carbon::parse($value)->toDateString();
    }


    public function getCoordinatesAttribute($coordinates)
    {
        return json_decode($coordinates);

    }


    public function getExpiredDaysAttribute()
    {
        return Carbon::now()->diffInDays($this->expired_at, false);
    }

    public function getIsExpiredAttribute()
    {
        if ($this->is_trial_verison) {
            return true;
        }
        if (is_null($this->expired_at)) {

            return true;
        }

        return Carbon::now()->diffInDays($this->expired_at, false) <= 0;
    }

    //同事
    public function members()
    {
        return $this->belongsToMany(
            User::class,
            'company_administrator_relation',
            'company_id',
            'user_id'
        );
    }

    /**
     *店铺所属平台角色.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(CompanyRole::class, 'role_id');
    }


    //创建人
    public function user()
    {

        return $this->belongsTo(User::class, 'user_id', 'id');

    }

    public function users()
    {
        return $this->belongsToMany(
            User::class,
            'user_company',
            'company_id',
            'user_id'
        );
    }


}